<template>
  <div id="map" class="map">
    <TyphoonInfo ref="typhoonInfo" :closeInfo="closeInfo" :typhoonData="typhoonData" />
    <div v-drag v-if="showDialog"
      style="position: absolute;right: 5%;top:40%;height:500px;width: 700px;z-index: 9999999;  cursor: grab;">
      <dv-border-box-7 style="background: #0c215b8c">
        <InfoAsset :typhoonData="dialogData" :closeInfo2="closeInfo2" />
      </dv-border-box-7>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import { Point, LineString } from "ol/geom";
import { fromLonLat } from "ol/proj";
import { Fill, Circle, Style, Stroke } from "ol/style";
import XYZ from "ol/source/XYZ";
import { defaults as defaultControls } from "ol/control";
import { getDataCenterPoint, asnpoint, asnConnect, getDataCenterListNew } from "@/api/map";

import TyphoonInfo from "./typhoonInfo.vue";
import InfoAsset from './info.vue'
import Overlay from "ol/Overlay";
export default {
  name: "HelloWorld",
  components: {
    TyphoonInfo, InfoAsset
  },
  data() {
    return {
      map: null,
      resPdata: [],
      lineData: [],
      linePointData: [],
      typhoonData: {},
      tfInfoOverlay: null,
      lastZoomPoint: null,
      showDialog: false,
      dialogData: null,
      currentPopup: null, // 当前被选中的悬浮框
      centerPdata: []
    };
  },
  // 自定义指令 实现可拖动
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var disx = e.pageX - el.offsetLeft
        var disy = e.pageY - el.offsetTop
        document.onmousemove = function (e) {
          el.style.left = e.pageX - disx + 'px'
          el.style.top = e.pageY - disy + 'px'
        }
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null
        }
      }
    }
  },

  mounted() {
    this.initMap();
    this.getMap();
    this.addOverlay();
    this.$store.state.switch.isHidden = true;
  },
  methods: {
    showPopupOnZoomLevel() {
      console.log(`output->dddd`)
    },
    // 关闭窗口显示
    closeInfo: function () {
      this.tfInfoOverlay.setPosition(undefined);
    },
    // 关闭窗口显示
    closeInfo2() {
      if (this.currentPopup) {
        this.changePopupColor(this.currentPopup, '#4874cb');
      }
      // 重置 currentPopup 为 null
      this.currentPopup = null;
      // 关闭弹框
      this.showDialog = false;
    },

    // 添加弹框
    addOverlay: function () {
      var popup = new Overlay({
        element: this.$refs.typhoonInfo.$el,
        // autoPan: true,
      });
      popup.setPosition(undefined);
      this.tfInfoOverlay = popup;
      this.map.addOverlay(popup);
    },

    // 数据中心
    centerPoint() {
      getDataCenterListNew().then((res) => {
        this.centerPdata = res.data
        let data = []
        for (var i = 0; i < this.centerPdata.length; i++) {
          if (this.centerPdata[i] && this.centerPdata[i].longitude && this.centerPdata[i].latitude) {
            data.push(this.centerPdata[i])
          }
        }

        let points = data;
        let features = [];
        // console.log('points', points);

        for (let i = 0; i < data.length; i++) {
          let position = [points[i].longitude, points[i].latitude];

          let positionArr = fromLonLat(position)
          // console.log('positionArr', positionArr);

          if (!isNaN(positionArr[0]) && !isNaN(positionArr[1])) {
            let featurePoint = new Feature({
              geometry: new Point(positionArr),
            });

            featurePoint.setStyle(
              new Style({
                image: new Circle({
                  fill: new Fill({
                    color: "#00B0FF",
                  }),
                  radius: 6,
                }),
              })
            );
            // 为点设置悬浮框
            let overlay = new Overlay({
              positioning: 'bottom-center', // 悬浮框定位方式
              element: this.createPopupContent(points[i]), // 创建悬浮框内容
              stopEvent: false, // 允许事件通过悬浮框传递到地图上
            });
            featurePoint.set('overlay', overlay); // 将悬浮框与点关联

            // console.log('@@points', points[i]);
            featurePoint.set('pointCenterData', points[i])
            features.push(featurePoint);
          }
        }
        // 矢量图层
        let layer = new VectorLayer();
        // 矢量数据源
        let source = new VectorSource({
          wrapX: false
        });
        source.addFeatures(features);
        layer.setSource(source);
        this.map.addLayer(layer);
        // 显示所有悬浮框
        features.forEach(feature => {
          this.setOverlayPosition22(feature.getGeometry().getCoordinates(), feature.get('overlay'));
        });
      })
    },
    // 初始化地图
    initMap() {
      this.map = new Map({
        layers: [
          new TileLayer({
            // 创建一个使用Open Street Map地图源的瓦片图层
            source: new XYZ({
              url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
              wrapX: false
            }),
          }),
        ],
        target: "map",
        view: new View({
          zoom: 3, // 缩放
          // projection: 'EPSG:4326', // 坐标系
          center: [0, 0], // 地图中心点
          // center: [0,0]
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false,
        }),
      });
      this.map.on('zoomend', this.showPopupOnZoomLevel);
    },

    // 获取后台数据
    getMap() {

      // this.drawTyphoonPath();
      //       this.drawLine();
      this.centerPoint()
      // this.designClickOnMap();
    },

    // 显示线
    drawLine() {
      let data = this.lineData;
      let len = data.length;
      let layer = new VectorLayer();
      let source = new VectorSource({
        wrapX: false
      });

      // 创建线样式
      let redDashedLineStyle = new Style({
        stroke: new Stroke({
          color: "#286be9", // 线条颜色设置为红色
          width: 1, // 线条宽度
          // lineDash: [2, 3], // 虚线的模式，这里设置为10像素的实线和10像素的空白交替出现
        }),
      });
      // 创建绿色点样式
      let greenPointStyle = new Style({
        image: new Circle({
          radius: 2, // 点的大小
          fill: new Fill({
            color: "#7998bb",
          }),
        }),
      });
      // 遍历lineData数组
      for (let i = 0; i < len; i++) {
        let currentData = data[i];
        let startPos = [currentData.srcLongitude, currentData.srcLatitude];
        let endPos = [currentData.dscLongitude, currentData.dscLatitude];

        // 创建线Feature
        let feature = new Feature({
          geometry: new LineString([fromLonLat(startPos), fromLonLat(endPos)]),
        });
        feature.setStyle(redDashedLineStyle); // 应用样式到Feature

        // 创建起点和终点的点Feature
        let startFeature = new Feature({
          geometry: new Point(fromLonLat(startPos)),
        });
        let endFeature = new Feature({
          geometry: new Point(fromLonLat(endPos)),
        });
        startFeature.setStyle(greenPointStyle);
        endFeature.setStyle(greenPointStyle); // 应用绿色点样式到终点Feature

        // 将Feature添加到VectorSource中
        source.addFeature(feature);
        source.addFeature(startFeature);
        source.addFeature(endFeature);
      }

      layer.setSource(source);
      this.map.addLayer(layer);
    },
    // 显示点
    drawTyphoonPath() {
      // let data = this.resPdata.filter(obj =>{ obj != null && obj.longitude && obj.latitude && obj.longitude > 0 && obj.latitude > 0 })
      // console.log(data)
      let data = [];
      for (var i = 0; i < this.resPdata.length; i++) {
        // console.log(this.resPdata[i])
        if (
          this.resPdata[i] &&
          this.resPdata[i].longitude &&
          this.resPdata[i].latitude &&
          this.resPdata[i].longitude > 0 &&
          this.resPdata[i].latitude > 0
        ) {
          data.push(this.resPdata[i]);
        }
      }

      let points = data;
      let features = [];
      let positions = [];
      for (let i = 0; i < data.length; i++) {
        let position = [points[i].longitude, points[i].latitude];
        var po = fromLonLat(position);
        // console.log(po)
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position)),
        });

        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: "#ffc0cb",
              }),
              radius: 6,
            }),
          })
        );
        console.log(`output->featurePoint`, featurePoint)
        // console.log('@@points', points[i]);
        featurePoint.set("pointData", points[i]);
        features.push(featurePoint);
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },
    // 创建悬浮框内容的函数
    createPopupContent(pointData) {
      // 这里可以根据 pointData 创建悬浮框的 HTML 内容
      // 例如：
      // console.log(`output->pointData`,pointData)
      let popupDiv = document.createElement('div');
      popupDiv.className = 'popup-bubble'
      // popupDiv.style.cssText = 'width: 150px; height: 80px; background-color: #4874cb; position: relative;padding: 10px;color:black;line-height:1.3';

      // 添加第一行文本“详细信息”
      let detailInfo = document.createElement('p');
      detailInfo.style.cssText = "font-size:17px;margin-bottom:5px"
      detailInfo.textContent = pointData.availableAreas;
      popupDiv.appendChild(detailInfo);

      // 添加第二行文本，地名
      let placeName = document.createElement('p');
      placeName.style.cssText = "text-align: left;color: #ffffffc7;"

      placeName.textContent = `云服务数量: ${pointData.cloudServerCount}`; // 假设地名存储在 pointData.countryNameCn 中
      popupDiv.appendChild(placeName);

      // 添加第三行文本，经纬度
      let coordinatesInfo = document.createElement('p');
      coordinatesInfo.style.cssText = "text-align: left;color: #ffffffc7;"

      coordinatesInfo.textContent = `云组件数量: ${pointData.cloudConponentSize}`;
      popupDiv.appendChild(coordinatesInfo);

      // 创建按钮并添加到div中
      let closeButton = document.createElement('button');
      closeButton.className = 'popupBut'

      closeButton.innerHTML = '详情';

      // 绑定点击事件到closeButton
      closeButton.onclick = () => {



        // 检查是否有当前选中的popupDiv
        if (this.currentPopup) {
          // 重置之前选中的popupDiv背景颜色
          this.changePopupColor(this.currentPopup, '#4874cb', '99999');

        }
        // 改变当前点击的closeButton的popupDiv背景颜色为绿色
        this.changePopupColor(popupDiv, '#003cb2', '999999');
        // 更新当前选中的popupDiv为当前的popupDiv
        this.currentPopup = popupDiv;

        // 调用gohome方法，可以在这里添加额外的逻辑
        this.gohome(pointData);
        let longitude = pointData.longitude;
        let latitude = pointData.latitude;
        this.zoomToLevel(7, longitude, latitude);
        // this.zoomToLevel(5);
      };
      // 将按钮添加到popupDiv中
      popupDiv.appendChild(closeButton);

      return popupDiv;
    },
    changePopupColor(popupElement, color, index) {
      popupElement.style.backgroundColor = color;
      popupElement.style.zIndex = index;
    },
    // ...其他方法...

    zoomToLevel: function (level, longitude, latitude) {
      if (this.map) {
        // 将经纬度转换为地图的投影坐标系
        let centerPoint = fromLonLat([longitude, latitude]);
        // 设置地图的中心点和缩放级别
        this.map.getView().setCenter(centerPoint);
        this.map.getView().setZoom(level);
      }
    },
    gohome(data) {
      this.dialogData = data
      // 这里是gohome方法的实现，例如跳转到首页
      this.showDialog = true
      // 可以在这里添加跳转逻辑，例如使用Vue Router进行页面跳转
      // this.$router.push({ path: '/home' });
    },
    // 设置悬浮框位置的函数
    setOverlayPosition22(coordinates, overlay) {
      overlay.setPosition(coordinates);
      this.map.addOverlay(overlay);
      overlay.setVisible(true); // 确保悬浮框是可见的
    },

    // 设置overlay position
    setOverlayPosition: function (position) {
      let transferPosition = fromLonLat(position);
      this.tfInfoOverlay.setPosition(transferPosition);
    },

    // 注册一个click事件
    designClickOnMap: function () {
      let _this = this;
      this.map.on("pointermove", function (ev) {
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height];
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(pix, function (feature) {
          return feature;
        });
        if (feature && feature.get("pointData")) {
          console.log(`output->`, feature);
          _this.map.getTargetElement().style.cursor = "pointer";
          // feature.getStyle().getImage().setRadius(10);
          feature.setStyle(
            new Style({
              image: new Circle({
                fill: new Fill({
                  color: "red",
                }),
                radius: 10,
              }),
            })
          );
          // 这里是改变点的颜色
          // 修改点的颜色
          // feature.getStyle().getImage().setFill({
          //   color: 'green', // 新的颜色值
          // });
          feature.changed();
          let point = feature.get("pointData");
          let position = [point.longitude, point.latitude];

          _this.lastZoomPoint = feature;
          // console.log(point);
          _this.setOverlayPosition(position);
          _this.typhoonData = point;
          // console.log(`output->this.typhoonData`, _this.typhoonData);
          // _this.$store.state.switch.showDetail = true;
          // console.log(`output->`, feature.values_.pointData)
        } else {
          _this.closeInfo();
          _this.clearPointZoomStyle();
          _this.map.getTargetElement().style.cursor = "";
          // console.log("no feature");
          _this.$store.state.switch.showDetail = false;
          _this.$store.state.switch.showDetailTwo = false;
        }
      });
    },
    designPostCompose() {

    },
    // clearPoint Zoom Style
    clearPointZoomStyle: function () {
      let _this = this;
      if (_this.lastZoomPoint != null) {
        // console.log(`output->`, name);
        // _this.lastZoomPoint.getStyle().getImage().setRadius(6);
        _this.lastZoomPoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: "#ffc0cb",
              }),
              radius: 6,
            }),
          })
        );
        _this.lastZoomPoint.changed();
      }
    },
  },
};
</script>

<style lang="scss">
.map {
  width: 100%;
  height: 100%;
}

.popup-bubble {
  border-radius: 10%;
  position: relative;
  width: 100%;
  height: 70px;
  font-size: 13px;
  padding: 10px;
  background-color: #4874cbd6;
  color: rgb(255, 255, 255);
  line-height: 1.3;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  margin-bottom: 20px;
  /* 确保有足够的空间显示三角形 */

}

.popupBut {
  background: #00000000;
  position: absolute;
  right: 4px;
  bottom: 4px;
  border: none;
  color: #00b8ff;
  cursor: pointer;
  font-size: 13px;
}

.popup-bubble:after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -10px;
  /* 调整以在气泡下方显示三角形 */
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  /* 隐藏左边框 */
  border-right: 10px solid transparent;
  /* 隐藏右边框 */
  border-top: 10px solid #4874cb;
  /* 显示上边框，与气泡背景色一致 */
  margin-left: -10px;
  /* 调整三角形中心与气泡中心对齐 */
}
</style>
